package com.cainaer.product.controller;


import com.cainaer.common.core.utils.DateUtils;
import com.cainaer.common.core.utils.StringUtils;
import com.cainaer.common.core.utils.bean.BeanUtils;
import com.cainaer.common.core.web.controller.BaseController;
import com.cainaer.common.core.web.domain.AjaxResult;
import com.cainaer.product.domain.*;
import com.cainaer.product.domain.vo.ProductVo;
import com.cainaer.product.service.*;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author Tina
 * @since 2020-09-11
 */
@RestController
@RequestMapping("/commodity/")
public class ProductController extends BaseController {

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IProductCategoryService productCategoryService;

    @Autowired
    private IProductAttributeBindOptionService productAttributeBindOptionService;

    @Autowired
    private IProductAttributeOptionService productAttributeOptionService;

    @Autowired
    private IProductAttributeService productAttributeService;


    @Value("${pathFile.img}")
    private String pathFileImg;

    @Value("${fileTomcat.imgUrl}")
    private String fileTomcatImgUrl;

    private Logger logger = LoggerFactory.getLogger(ProductController.class);

    /**
     * 编辑商品
     *
     * @param product
     * @return
     */
    @PostMapping("edit")
    public AjaxResult editProduct(@RequestBody Product product) {
        logger.info("product->{}", product);
        if (StringUtils.isNull(product.getProductId())) {
            return AjaxResult.error("主键不能为空");
        }

        return toAjax(productService.editProduct(product));
    }

    /**
     * 新增商品
     *
     * @param productVo
     * @return
     */
    @PostMapping("add")
    @Transactional
    public AjaxResult insertProduct(@RequestBody ProductVo productVo) {

        // 新增商品表
        Product product = new Product();
        BeanUtils.copyProperties(productVo, product);
        product.setCreateTime(DateUtils.getTime());
        Integer insertProduct = productService.insertProduct(product);
        if (insertProduct > 0) {

            // 新增商品SKU表
            ProductSku productSku = new ProductSku();

            for (ProductSku productSkus : productVo.getProductSkus()) {
                BeanUtils.copyProperties(productSkus, productSku);
                productSku.setProductId(product.getProductId());
                productSkuService.insertProductSku(productSku);
            }

            //新增商品属性表
            List<ProductAttributeOption> attributeOptions = productVo.getProductAttributeOption();
            ProductAttribute productAttributeTwo = new ProductAttribute();
            ProductAttributeBindOption productAttributeBindOption = new ProductAttributeBindOption();
            productAttributeBindOption.setCreateTime(DateUtils.getTime());

            for (ProductAttributeOption attributeOption : attributeOptions) {


                attributeOption.setCreateTime(DateUtils.getTime());
                //新增商品属性表
                productAttributeOptionService.insertProductAttributeOption(attributeOption);
                productAttributeBindOption.setOptionId(attributeOption.getOptionId());

                //新增自定义商品规格表
                for (ProductAttribute attribute : attributeOption.getProductAttributesList()) {
                    BeanUtils.copyProperties(attribute, productAttributeTwo);
                    attribute.setCreateTime(DateUtils.getTime());
                    attribute.setProductId(product.getProductId());
                    productAttributeService.insertProductAttribute(attribute);
                    productAttributeBindOption.setAttributeId(attribute.getAttributeId());

                    // 新增规格属性绑定表
                    productAttributeBindOptionService.insertProductAttributeBindOption(productAttributeBindOption);
                }

            }
        }

        return toAjax(insertProduct);
    }


    /**
     * 查询商品信息
     *
     * @return
     */
    @GetMapping("list")
    public AjaxResult selectProduct(Product product, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        return AjaxResult.success(productService.selectProduct(product, pageNum, pageSize));
    }

    /**
     * 上传商品图
     *
     * @param file
     * @return
     */
    @PostMapping("productImg/{shopId}")
    public AjaxResult productImg(@RequestParam("file") MultipartFile file, Long shopId) throws IOException {

        System.out.println("shopId->" + shopId);
        if (StringUtils.isNull(shopId)) {
            return AjaxResult.error("主键不能为空");
        }

        if (!file.isEmpty()) {
            // 获取文件并将其保存在某处
            String url = pathFileImg + "productImg/" + shopId + "/";
            String fileUrlTomcat = fileTomcatImgUrl + "productImg/" + shopId + "/";
            String myFileOriginalFilename = file.getOriginalFilename();
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(url, myFileOriginalFilename));
            return AjaxResult.success(200, fileUrlTomcat + myFileOriginalFilename);
        }
        return AjaxResult.error();
    }

    /**
     * 查询商品
     *
     * @param product
     * @return
     */
    @GetMapping("selectProduct")
    public AjaxResult selectProduct(Product product) {
        if (StringUtils.isNull(product.getShopId())) {
            return AjaxResult.error("主键不能为空");
        }
        return AjaxResult.success(productService.selectProduct(product));
    }

    /**
     * 查询商品详情消息
     *
     * @param productId
     * @return
     */
    @GetMapping("select/{productId}")
    public AjaxResult selectProductInfo(@PathVariable Long productId) {
        List list = new LinkedList();
        list.add(productService.selectProductInfo(productId));
        list.add(productAttributeService.selectProductAttribute(productId));
        return AjaxResult.success(list);
    }


    @GetMapping("query/{productId}")
    public AjaxResult queryEditProductInfo(@PathVariable Long productId) {
        List list = new LinkedList();
        list.add(productService.selectProductInfo(productId));

        return AjaxResult.success(list);
    }


}
